package com.jimmyapp.papa.game.logic;

import java.util.LinkedList;

import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView;
import android.util.Log;

import com.jimmyapp.papa.game.GameListener;
import com.jimmyapp.papa.game.model.Box;

public class DropBoxGameLogic implements GameLogic{
	public int score = 0;
	public int position =0;
	public LinkedList<Box> boxs;
	private int boxNum = 2;
	private float[] xt = new float[10];
	private float[] yt = new float[10];
	private float[] zt = new float[10];
	private float[] xr = new float[10];
	private float[] yr = new float[10];
	private float[] zr = new float[10];
	private float[] ar = new float[10];
	//private LinkedList<Float> xt
	public DropBoxGameLogic() {
		boxs = new LinkedList<Box>();
		initArray();
	}
	public void initArray() {
		float level = 2.5f;
		boxNum = Math.min(2 + score/10, 10);
		synchronized(boxs) {
			boxs.clear();
			for(int i=boxNum-1;i>=0;i--) {
				boxs.add(new Box());
				xt[i] = (float)(Math.random()*4-2f);
				yt[i] =  level;
				//zt[i] = -7f;
				xr[i] = (float)Math.random()*4-2f;
				yr[i] = (float)Math.random()*4-2f;
				zr[i] = (float)Math.random();
				ar[i] = (float)Math.random()*180;
				level += (float)Math.random()*2f+ 1.5f;
			}
		}
	}
	
	@Override
	public void draw(GL10 gl) {
		synchronized(boxs) {
			int size = boxs.size();
			for (int i=0;i<size;i++) {
				gl.glPushMatrix();
				gl.glTranslatef(xt[i],yt[i],-7f);
				gl.glRotatef(ar[i], xr[i], yr[i], zr[i]);
				boxs.get(i).draw(gl);
				gl.glPopMatrix();
			}
		}
	}
	@Override
	public boolean pick(int color) {
		synchronized(boxs) {
			if (boxs.getLast().color == color) {
				boxs.removeLast();
				if(boxs.isEmpty()) {
					score +=5;
					initArray();
				}
				return true;
			}
			return false;
		}
	}
	@Override
	public int getScore() {
		return score;
	}
	@Override
	public void resetScore() {
		score = 0;
	}
	@Override
	public void run() {
		while (running) {
			for(int i=boxNum-1;i>=0;i--) {
				yt[i] -= 0.4f;
				xr[i] += 0.2f;
				if (yt[i] <= -8.0f) {
					listener.fail();
					initArray();
					break;
				}
			}
			Log.d("inrunning", "score is"+score);
			view.requestRender();
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		running = true;
	}
	private GameListener listener;
	@Override
	public void addGameListener(GameListener gameListener) {
		listener = gameListener;
	}
	private boolean running = true;
	@Override
	public void stopGame() {
		running = false;
		initArray();
	}
	private GLSurfaceView view;
	@Override
	public void addView(GLSurfaceView glView) {
		view = glView;
	}
	
}
